from django.db import connection


def cart_count(request):
    """
    上下文处理器：获取用户购物车商品数量
    用于在导航栏显示购物车数量
    """
    cart_count = 0
    
    if request.user.is_authenticated:
        try:
            with connection.cursor() as cursor:
                cursor.execute("""
                    SELECT SUM(quantity)
                    FROM tb_cart
                    WHERE user_id = %s
                """, [request.user.user_id])
                
                result = cursor.fetchone()
                if result and result[0]:
                    cart_count = result[0]
        except:
            # 出错时默认为0
            cart_count = 0
    
    return {'cart_count': cart_count} 